package org.yray.sip.base;



import org.apache.commons.lang3.StringUtils;

import java.util.LinkedHashMap;
import java.util.Map;

/***
 * Authorization: Digest username="78002", realm="172.130.13.31",
 * nonce="a88c768e-3842-423e-99f5-6bafa1636005", uri="sip:172.130.13.31:15060",
 * response="c8ee98a161f1f25d8f434c0b488d6eac", algorithm=MD5,
 * cnonce="4b030202497c43e380a13e012913a996",
 * qop=auth, nc=00000001
 */
public class Authorization {

    public static final  String USERNAME="username";
    public static final  String REALM="realm";
    public static final  String NONCE="nonce";
    public static final  String URI="uri";
    public static final  String RESPONSE="response";
    public static final  String ALGORITHM="algorithm";
    public static final  String CNONCE="cnonce";
    public static final  String QOP="qop";
    public static final  String NC="nc";
    private String tag;
    private String lineName;
    private Map<String,String> eleMap;

    public Authorization (String msg)
    {
        lineName=msg.substring(0,msg.indexOf(MsgEle.ELE_SEPARATOR));
        msg=msg.substring(msg.indexOf(MsgEle.ELE_SEPARATOR)+1).trim();
        createAuthorization(msg,lineName);

    }
    private void createAuthorization(String msg,String lineName)
    {
        this.lineName=lineName;
        msg=msg.trim();
        tag=msg.substring(0,msg.indexOf(' '));
        msg=msg.substring(msg.indexOf(' ')+1);
        eleMap=new LinkedHashMap<>();
        String[] eles=msg.split(MsgEle.AUTHORIZATION_ELE_SEPARATOR);
        for(String ele:eles)
        {
            String[] keyVal= ele.split(MsgEle.AUTHORIZATION_ELE_KEY_SEPARATOR);
            eleMap.put(StringUtils.trim(keyVal[0]),keyVal[1].replace("\"",""));
        }
    }
    public Authorization (String msg,String lineName)
    {
        createAuthorization(msg,lineName);
    }

    public Map<String, String> getEleMap() {
        return eleMap;
    }

    public void setEleMap(Map<String, String> eleMap) {
        this.eleMap = eleMap;
    }

    @Override
    public String toString()
    {
        StringBuilder sb=new StringBuilder(lineName+":"+tag+" ");
        for(Map.Entry entry:eleMap.entrySet())
        {
            sb.append(" ").append(entry.getKey()).append(MsgEle.AUTHORIZATION_ELE_KEY_SEPARATOR).append("\"").append(entry.getValue()).append("\",");
        }
        sb.deleteCharAt(sb.length()-1);
        return sb.toString();
    }


}
